package com.xiaomi.dao.impl;

import com.xiaomi.dao.OrderDao;
import com.xiaomi.entity.Address;
import com.xiaomi.entity.Orders;
import com.xiaomi.utils.C3P0Utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author jy
 * @date 2021/5/26
 */
public class OrderDaoImpl implements OrderDao {

    private final QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

    @Override
    public int insertOrder(Orders orders) throws Exception {
        Object[] objects = {orders.getOid(), orders.getUid(), orders.getAid(), orders.getMoney(), orders.getState(), orders.getTime()};
        String sql = "insert into orders values(?,?,?,?,?,?)";
        return queryRunner.update(sql, objects);
    }

    @Override
    public List<Orders> getOrderSetAddress(int uid) throws Exception {
        String sql = "select * from orders o,address a where o.aid=a.aid and o.uid=?";
        List<Map<String, Object>> maps = queryRunner.query(sql, new MapListHandler(), uid);
        List<Orders> list = new ArrayList<>();
        if (maps != null) {
            for (Map<String, Object> map : maps) {
                Orders orders = new Orders();
                Address address = new Address();
                BeanUtils.populate(orders, map);
                BeanUtils.populate(address, map);
                orders.setAddress(address);
                list.add(orders);
            }
            return list;
        }
        return null;
    }

    @Override
    public Orders getOrder(String oid) throws Exception {
        String sql = "select * from orders o,address a where o.aid=a.aid and oid=?";
        Map<String, Object> map = queryRunner.query(sql, new MapHandler(), oid);
        if (map != null) {
            Orders orders = new Orders();
            Address address = new Address();
            BeanUtils.populate(orders, map);
            BeanUtils.populate(address, map);
            orders.setAddress(address);
            return orders;
        }
        return null;
    }
}
